#include "http.h"

int SendHTTPPost(const char * pcData, int iDataSize)
{
    WSADATA  wsaData;
    if (WSAStartup(0x0101, &wsaData))
    {
        printf("WSAStartup failed\n");
        return FALSE;
    }

    SOCKET clientSocket = socket(AF_INET, 1, 0);

    struct sockaddr_in ServerAddr = { 0 };
    ServerAddr.sin_addr.s_addr = inet_addr(g_stCmdArg.m_acIP);
    ServerAddr.sin_port = htons(g_stCmdArg.m_iPort);
    ServerAddr.sin_family = AF_INET;
    int iRet = connect(clientSocket, (sockaddr*)&ServerAddr, sizeof(ServerAddr));
    if (iRet != 0)
    {
        printf("connect failed");
        return -1;
    }

    char acSendBuf[40960] = { 0 };
    char acHead[10240] = { 0 };
    char acFirstLine[1024] = { 0 };

    /***  head  ***/
    sprintf(acFirstLine, "%s %s HTTP/1.1\r\n", g_stCmdArg.m_acHTTPType, g_stCmdArg.m_acURI);

    char *pcCommonHead = 
        "Connection:Keep-Alive\r\n"
        "Accept-Encoding:gzip, deflate\r\n"
        "Accept-Language:zh-CN,en,*\r\n"
        "Content-Type:application/json; charset=UTF-8\r\n"
        "User-Agent:Mozilla/5.0\r\n";

    char acHost[1024] = { 0 };
    sprintf(acHost, "host:%s\r\n", g_stCmdArg.m_acIP);
    char acContentLength[1024] = { 0 };
    sprintf(acContentLength, "Content-Length:%d\r\n", iDataSize);

    strcpy(acHead, acFirstLine);
    strcat(acHead, pcCommonHead);
    strcat(acHead, acHost);
    strcat(acHead, acContentLength);

    strcpy(acSendBuf, acHead);
    strcat(acSendBuf, "\r\n");
    strcat(acSendBuf, pcData);

    cout << strlen(acSendBuf) << endl;
    cout << acSendBuf << endl;

    iRet = send(clientSocket, acSendBuf, strlen(acSendBuf), 0);
    if (iRet < 0)
    {
        cout << "send failed\n";
        return -1;
    }

    cout << "send success\n";
    return 0;
}

